package com.lonely.fx.key;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 * @date: 2022-07-27 12:26
 * @author: ztkj-hzb
 * @description: 键盘事件 属性设置
 **/
public class KeyEventSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox = new HBox();
        hBox.setSpacing(50);
        hBox.setPadding(new Insets(50));

        Button button = new Button("Button");
        TextField textField = new TextField();


        //键盘按下事件---如果按着不松开，会一直触发该事件
        button.setOnKeyPressed(event -> {

            //获取事件源，即是哪个组件触发的键盘按下事件
            Object source = event.getSource();
            //System.out.println(source);

            //几个常见的按键类型判断
            //System.out.println("是否是 Ctrl 键："+ event.isControlDown());
            //System.out.println("是否是 Alt 键："+ event.isAltDown());
            //System.out.println("是否是 Meta 键："+ event.isMetaDown());
            //System.out.println("是否是 Shift 键："+ event.isShiftDown());
            //System.out.println("是否是 平台兼容 键："+ event.isShortcutDown());

            //获取按键对象
            KeyCode code = event.getCode();
            System.out.println("按下的键是：" + code.getName());

            //获取事件类型
            EventType<KeyEvent> eventType = event.getEventType();
            System.out.println("事件类型：" + eventType.getName());

            //获取按钮的文本
            String text = event.getText();
            System.out.println("按键文本：" + text);

            //TODO 这个方法 与 setOnKeyTyped 配合使用
            String character = event.getCharacter();
            System.out.println("按键字符：" + character);

        });

        //文本框获取焦点后，输入数据，触发事件
        textField.setOnKeyTyped(event -> {
            String character = event.getCharacter();
            System.out.println("输入的字符：" + character);
        });

        //按键松开触发事件
        button.setOnKeyReleased(event -> {
            KeyCode code = event.getCode();
            System.out.println("松开按键：" + code.getName());
        });


        hBox.getChildren().addAll(button, textField);
        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();

    }
}
